package com.myhome.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.myhome.config.constant.R;
import com.myhome.domain.CashRecharge;
import com.myhome.domain.CashRechargeAuditRecord;
import com.myhome.model.CashParam;
import com.myhome.service.CashRechargeService;
import com.myhome.util.ReportCsvUtils;
import com.myhome.vo.BuyCashRechargeVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.util.CsvContext;
import springfox.documentation.annotations.ApiIgnore;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Author QYiXin
 * @Date 2021 10 20 16 37
 **/
@RestController
@Api(tags = "GCN充值控制器")
@RequestMapping("/cashRecharges")
public class CashRechargeController {
    @Autowired
    CashRechargeService cashRechargeService;

    @GetMapping("/records")
    @ApiOperation(value = "条件分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "size", value = "每页显示的条数"),
            @ApiImplicitParam(name = "coinId", value = "币种的Id"),
            @ApiImplicitParam(name = "userId", value = "用户的Id"),
            @ApiImplicitParam(name = "userName", value = "用户的名称"),
            @ApiImplicitParam(name = "mobile", value = "用户的手机号"),
            @ApiImplicitParam(name = "status", value = "充值审核状态"),
            @ApiImplicitParam(name = "numMin", value = "充值最小金额"),
            @ApiImplicitParam(name = "numMax", value = "充值最大金额"),
            @ApiImplicitParam(name = "startTime", value = "充值开始时间"),
            @ApiImplicitParam(name = "endTime", value = "充值结束时间"),

    })
    public R<Page<CashRecharge>> findByPage(
            @ApiIgnore Page<CashRecharge> page,
            Long coinId, Long userId, String userName,
            String mobile, Byte status, String numMin, String numMax,
            String startTime, String endTime
    ) {
        Page<CashRecharge> result = cashRechargeService.getPageCashRecharge(
                page, coinId, userId, userName,
                mobile, status, numMin, numMax,
                startTime, endTime
        );
        return R.ok(result);
    }

    @GetMapping("/records/export")
    @ApiOperation(value = "条件分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "coinId", value = "币种的Id"),
            @ApiImplicitParam(name = "userId", value = "用户的Id"),
            @ApiImplicitParam(name = "userName", value = "用户的名称"),
            @ApiImplicitParam(name = "mobile", value = "用户的手机号"),
            @ApiImplicitParam(name = "status", value = "充值审核状态"),
            @ApiImplicitParam(name = "numMin", value = "充值最小金额"),
            @ApiImplicitParam(name = "numMax", value = "充值最大金额"),
            @ApiImplicitParam(name = "startTime", value = "充值开始时间"),
            @ApiImplicitParam(name = "endTime", value = "充值结束时间"),

    })
    public void reportCashRecharge(
            Long coinId, Long userId, String userName,
            String mobile, Byte status, String numMin, String numMax,
            String startTime, String endTime
    ) {
        Page<CashRecharge> page = new Page<>(1, 10000);
        Page<CashRecharge> pageResult = cashRechargeService.getPageCashRecharge(
                page, coinId, userId, userName,
                mobile, status, numMin, numMax,
                startTime, endTime
        );
        String[] header = {"ID", "用户ID", "用户名", "真实用户名", "充值币种", "充值金额", "手续费", "到账金额", "充值方式", "充值订单", "参考号", "充值时间", "完成时间", "状态", "审核备注", "审核级数"};
        String[] properties = {"id", "userId", "username", "realName", "coinName", "num", "fee", "mum", "type", "outtradeno", "remark", "created", "lastTime", "status", "auditRemark", "step"};
        List<CashRecharge> records = pageResult.getRecords();
        if (!CollectionUtil.isEmpty(records)) {
            CellProcessor longToStringConvert = new CellProcessor() {
                @Override
                public <T> T execute(Object o, CsvContext csvContext) {
                    return (T) String.valueOf(o);
                }
            };
            DecimalFormat decimalFormat = new DecimalFormat("0.00000000");
            CellProcessor moneyConvert = new CellProcessor() {
                @Override
                public <T> T execute(Object o, CsvContext csvContext) {
                    BigDecimal num = (BigDecimal) o;
                    return (T) decimalFormat.format(num);
                }
            };
            CellProcessor typeConvert = new CellProcessor() {
                @Override
                public <T> T execute(Object o, CsvContext csvContext) {
                    String type = String.valueOf(o);
                    //类型：alipay，支付宝；cai1pay，财易付；bank，银联；
                    switch (type) {
                        case "alipay":
                            type = "支付宝";
                            break;
                        case "cai1pay":
                            type = "财易宝";
                            break;
                        case "bank":
                            type = "银联";
                            break;
                        default:
                            type = "未知";
                    }
                    return (T) type;
                }
            };
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MMM-dd");
            CellProcessor timeConvert = new CellProcessor() {
                @Override
                public <T> T execute(Object o, CsvContext csvContext) {
                    String timeFormat = simpleDateFormat.format((Date) o);
                    return (T) timeFormat;
                }
            };
            CellProcessor statusConvert = new CellProcessor() {
                @Override
                public <T> T execute(Object o, CsvContext csvContext) {
                    //状态：0-待审核；1-审核通过；2-拒绝；3-充值成功；
                    Integer type = (Integer) o;
                    String result = "";
                    switch (type) {
                        case 0:
                            result = "待审核";
                            break;
                        case 1:
                            result = "审核通过";
                            break;
                        case 2:
                            result = "拒绝";
                            break;
                        case 3:
                            result = "重置成功";
                            break;
                        default:
                            result = "未知";
                    }
                    return (T) result;
                }
            };
            CellProcessor[] PROCESSORS = new CellProcessor[]{longToStringConvert, longToStringConvert, null, null, null
                    , moneyConvert, moneyConvert, moneyConvert, typeConvert
                    , null, null, timeConvert, timeConvert, null, null, null};
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            try {
                ReportCsvUtils.reportListCsv(requestAttributes.getResponse(), header, properties, "场外交易充值审核.csv", records, PROCESSORS);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @GetMapping("/user/records")
    @ApiOperation(value = "查询当前用户的充值记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "size", value = "每页显示的大小"),
            @ApiImplicitParam(name = "status", value = "充值的状态"),
    })
    public R<Page<CashRecharge>> getOneUserCashRecharge(@ApiIgnore Page<CashRecharge> page, Byte status) {
        Long userId = Long.valueOf(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        page.addOrder(OrderItem.desc("last_update_time"));
        Page<CashRecharge> result = cashRechargeService.getOneUserCashRecharge(page, status, userId);
        return R.ok(result);
    }

    @PostMapping("/buy")
    @ApiOperation(value = "GCN的充值操作")
    @ApiImplicitParams({
            @ApiImplicitParam( name = "cashParam",value = "现金交易的参数")
    })
    public R<BuyCashRechargeVo> buyCashRecharge(@RequestBody CashParam cashParam){
        Long userId = Long.valueOf(SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString());
        BuyCashRechargeVo result = cashRechargeService.buyCashRecharge(userId,cashParam);
        return R.ok(result);
    }


}
